package org.light.framework.ioc;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import org.light.framework.ioc.annotation.Impl;
import org.light.framework.mvc.annotation.Inject;
import org.light.framework.util.ArrayUtil;
import org.light.framework.util.ClassUtil;
import org.light.framework.util.CollectionUtil;
import org.light.framework.util.ReflectionUtil;

public class IocHelper {
	static {

		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		if (beanMap != null && !beanMap.isEmpty()) {
			for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
				Class<?> beanClass = beanEntry.getKey();
				Object beanInstance = beanEntry.getValue();
				Field[] beanFields = beanClass.getDeclaredFields();
				if (ArrayUtil.isNotEmpty(beanFields)) {
					for (Field beanField : beanFields) {
						// 判断当前Field是否带有Inject注解
						if (beanField.isAnnotationPresent(Inject.class)) {
							Class<?> interfaceClass = beanField.getType();
							Class<?> implementClass = findImplementClass(interfaceClass);
							if (implementClass != null) {
								Object beanFieldInstance = beanMap.get(implementClass);
								if (beanFieldInstance != null) {
									ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
								}
							} else {
								System.out.println("未找到接口 " + interfaceClass + " 的实现类");
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 查找实现类
	 */
	public static Class<?> findImplementClass(Class<?> interfaceClass) {
		Class<?> implementClass = interfaceClass;
		// 判断接口上是否标注了 Impl 注解
		if (interfaceClass.isAnnotationPresent(Impl.class)) {
			// 获取强制指定的实现类
			implementClass = interfaceClass.getAnnotation(Impl.class).value();
		} else {
			// 获取该接口所有的实现类
			List<Class<?>> implementClassList = ClassUtil.getClassListBySuper(interfaceClass);
			if (CollectionUtil.isNotEmpty(implementClassList)) {
				// 获取第一个实现类
				implementClass = implementClassList.get(0);
			}
		}
		// 返回实现类对象
		return implementClass;
	}

}
